const express = require('express');
const axios = require('axios');

const router = express.Router();

const detailParser = {
    'AdvNN-W': (data) => {
        if (data && data.result && data.result.task) {
            const {
                task_desc: Description,
                module_name: Name,
                status: Status,
            } = data.result.task;
    
            return {
                Name,
                Description,
                Status,
            };
        } else {
            return {};
        }
    },
    'AdvNN-B': (data) => {
        if (data && data.result && data.result.task) {
            const {
                task_desc: Description,
                module_name: Name,
                status: Status,
            } = data.result.task;
    
            return {
                Name,
                Description,
                Status,
            };
        } else {
            return {};
        }
    },
    'ExpNN': (data) => {
        if (data && data.data) {
            const {
                taskDesc: Description,
                taskName: Name,
                status: Status,
            } = data.data;
            
            return {
                Name,
                Description,
                Status,
            };
        } else {
            return {};
        }
    },
    'RobNN': (data) => {
        if (data && data.data) {
            const {
                taskDesc: Description,
                taskName: Name,
                status: Status,
            } = data.data;
    
            return {
                Name,
                Description,
                Status,
            };
        } else {
            return {};
        }
    },
};

const getTaskDetail = (api, tid, tool) => {
    if (!api || !tid || !tool) return {};

    return new Promise((resolve, reject) => {
        axios.get(`${api}${tid}`).then((res) => {
            if (res.data.code === '202') {
                // 任务不存在
                resolve('need-to-delete');
            } else if (res.data) {
                resolve(detailParser[tool] ? detailParser[tool](res.data) : {});
            } else {
                resolve({});
            }
        }).catch(() => {
            reject();
        });
    })
}

router.get('/', 
    async (req, res, next) => {
        const user = req.user && req.user.id;
        if (!user) {
            return next('route');
        }

        // query
        res.locals.filter = Object.assign(
            {}, 
            res.locals.filter, 
            { User: user },
        );

        res.locals.fields = [
            'id',
            'LastUpdateDate',
            
            // 'User',
            'Tool',
            'Name',
            'Description',
            'Status',
            'tid',

            'noDetails',
            'Result',
        ];

        return next();
    }, 
    router.FindDocuments('tests', false, async (req, res) => {
        const docs = res.locals.data.docs || [];

        // let locale = req.query.locale;
        // locale = {
        //     'zh-cn': '中文',
        //     'en-us': '英文',
        // }[locale] || '中文';

        const tools = {};
        for (let i = 0 ; i < docs.length; i += 1) {
            const doc = docs[i];
            // if (!doc.tid) continue;

            let theTool = tools[doc.Tool] || await res.app.models.tool.findOne({
                代码: doc.Tool,
                // 语言: locale,
            });

            if (!theTool) {
                theTool = await res.app.models.tool.findOne({
                    id: doc.Tool,
                }).lean();

                // TODO: should not involve another type of tools...
                theTool = await res.app.models.industryeval.findOne({
                    id: doc.Tool,
                }).lean();
            }

            if (!theTool) continue;

            const latestDetails = doc.tid && theTool.detailsApi && await getTaskDetail(theTool.detailsApi, doc.tid, doc.Tool); 
            
            if (latestDetails === 'need-to-delete') {
                await res.app.models.tests.updateOne({
                    User: req.user.id,
                    tid: doc.tid,
                }, {$set: {Deleted: true}});

                docs[i] = null;
            } else if (latestDetails && Object.keys(latestDetails).length) {
                // update task result
                await res.app.models.tests.updateOne({
                    tid: doc.tid,
                    Tool: doc.Tool,
                },{$set: {
                    ... doc,
                    ... latestDetails,
                }});

                // modify for return
                docs[i] = {
                    ... doc,
                    ...latestDetails, 
                    Tool: theTool.标题,
                    代码: doc.Tool,
                    StatusLabel: router.mdl.t(
                        `taskStatus${latestDetails.Status}`, 
                        // req.query.locale
                    ),
                }
    
                delete doc.tid;
            } else {
                // modify for return
                docs[i] = {
                    ... doc,
                    ...latestDetails, 
                    Tool: theTool.标题 || theTool.名称,
                    StatusLabel: router.mdl.t(
                        `taskStatus${{
                            SUCCESS: 'FINISHED',
                            FAIL: 'FAILED',
                            CANCEL: 'CANCELED',
                            PENDING: 'PENDING',
                        }[doc.Status] || doc.Status}`, 
                        // req.query.locale
                    ),
                }
    
                delete doc.tid;
            }
        }

        res.locals.data.docs = res.locals.data.docs.filter((doc) => !!doc);
    }),
);

router.get('/:id', (req, res, next) => {
    res.locals.filter = {
        User: req.user.id,
        id: req.params.id,
    };

    res.locals.fields = [
        'tid',
        'Tool',
        'Status',
    ];

    return next();
}, router.FindDocuments('tests', false, async (req, res) => {
    res.locals.data = (res.locals.data.docs && res.locals.data.docs[0]) || {};

    const theTool = await res.app.models.tools.findOne({代码: res.locals.data.Tool});
    if (!theTool) {
        res.locals.data = {};
    } else {
        res.locals.data = {
            url: theTool.detailsPage.replace('{{USERID}}', req.user.id).replace('{{TASKID}}', res.locals.data.tid) + `&status=${res.locals.data.Status}`, 
            
        };
    }
}))

module.exports = router;
